/**
 * 
 */
package com.bestbuy.daoimple;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bestbuy.dao.PromotionDAO;
import com.bestbuy.pojo.Catalog;
import com.bestbuy.pojo.Product;
import com.bestbuy.pojo.Promotion;

/**
 * @author ThanhNgo
 *
 */
@Repository
@SuppressWarnings({ "unchecked", "rawtypes" })
public class PromotionDAOImpl implements PromotionDAO {

	@Autowired
	private SessionFactory sessionFactory;
	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#getListPromotion(java.lang.String)
	 */
	public List<Promotion> getListPromotion(String page) {
		Session session = sessionFactory.getCurrentSession();
		int temp = Integer.parseInt(page)-1;
		List<Promotion> promotions ;
		String sql = "from Promotion";
		Query query = session.createQuery(sql);
		query.setFirstResult(temp*5);
		query.setMaxResults(5);
		promotions = (List<Promotion>) query.list();
		return promotions;
	}

	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#updatePromotion(com.bestbuy.pojo.Promotion)
	 */
	public void updatePromotion(Promotion promotion) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		session.save(promotion);
	}

	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#savePromotion(com.bestbuy.pojo.Promotion)
	 */
	public void savePromotion(Promotion promotion) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		session.save(promotion);
	}

	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#countProduct()
	 */
	public int countProduct() {
		Session session = sessionFactory.getCurrentSession();
		String sql = "select count(*) from Promotion";
		Query query = session.createQuery(sql);
		int count = ((Long) query.uniqueResult()).intValue();
		int page = count/5;
		int du = count%5;
		if(du>0)
		{
			page = page+1;
		}
		
		return page;
	}

	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#getPromotion(java.lang.String)
	 */
	public Promotion getPromotion(String idPromotion) {
		Session session = sessionFactory.getCurrentSession();
		String sql = "from Promotion where idpromotion = ?";
		Query query = session.createQuery(sql);
		query.setString(0, idPromotion);
		Promotion promotion = (Promotion)query.uniqueResult();

		
		return promotion;
	}

	/* (non-Javadoc)
	 * @see com.bestbuy.dao.PromotionDAO#getListPromotion()
	 */
	public List<Promotion> getListPromotion() {
		Session session = sessionFactory.getCurrentSession();
		String sql = "from Promotion";
		Query query = session.createQuery(sql);
		List<Promotion> promotions = (List<Promotion>) query.list();

		
		return promotions;
	}

}
